#include "zbGPIO.h"

#define myFlag enGPIO

void initGPIO()
{
	GPIO_InitTypeDef GPIO_InitStructure;
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
	// gpio for lights etc, basic 
	GPIO_InitStructure.GPIO_Pin =  GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
	GPIO_Init(GPIOC, &GPIO_InitStructure);
	// gpio for motors front,back,left,right
	GPIO_InitStructure.GPIO_Pin =  GPIO_Pin_6 | GPIO_Pin_7 | GPIO_Pin_8 | GPIO_Pin_9;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
	GPIO_Init(GPIOC, &GPIO_InitStructure);

	// write all to 0
	GPIO_Write(GPIOC, 0x00);
}

void disableGPIO()
{
	GPIO_Write(GPIOC, 0x00);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, DISABLE);
}

void updateGPIO()
{
	u8 cont = false;
	if(mygVars->enabled != newgVars->enabled)
	{
		// if we were off 
		if(!(mygVars->enabled & myFlag))
		{
			// and now we are on
			if(newgVars->enabled & myFlag)
			{
				initGPIO();
				// update to know that we are on now
				mygVars->enabled = (mygVars->enabled | myFlag);	
				cont = true;
			}
		}
		// if we were on
		if(mygVars->enabled & myFlag)
		{
			// and now we are off
			if(!(newgVars->enabled & myFlag))
			{
				disableGPIO();
				// clear bit so we are off next time
				mygVars->enabled = (mygVars->enabled & !myFlag);
			}
		}
	}
	
	// if we get to this point and we are disabled just ret
	if(!(mygVars->enabled & myFlag) && (cont == false))
	{
		return;
	}

	// if its actually a different value do something 
	if(mygVars->gpioWrite != newgVars->gpioWrite)
	{
		// update old value with new and update
		mygVars->gpioWrite = newgVars->gpioWrite;
		GPIO_Write( GPIOC, (u16)( mygVars->gpioWrite & 0xFFFF ) );
	}	
}


// unused ! 

// control jumpers
#define CTL_JMP1_CLK	RCC_APB2Periph_GPIOA
#define CTL_JMP1_PORT	GPIOA
#define CTL_JMP1_USER1	GPIO_Pin_0

#define CTL_JMP2_CLK	RCC_APB2Periph_GPIOC
#define CTL_JMP2_PORT	GPIOC
#define CTL_JMP2_USER2	GPIO_Pin_0

#define USRBTN1_H() 	GPIO_ReadInputDataBit(CTL_JMP1_PORT, CTL_JMP1_USER1)
#define USRBTN2_H() 	GPIO_ReadInputDataBit(CTL_JMP2_PORT, CTL_JMP2_USER2)

void initJumpers()
{
	GPIO_InitTypeDef GPIO_InitStructure;
	RCC_APB2PeriphClockCmd(CTL_JMP1_CLK | CTL_JMP2_CLK, ENABLE);
	// jumper for userbtn1
	GPIO_InitStructure.GPIO_Pin =  CTL_JMP1_USER1;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
	GPIO_Init(CTL_JMP1_PORT, &GPIO_InitStructure);
	// jumper for userbtn2
	GPIO_InitStructure.GPIO_Pin =  CTL_JMP2_USER2;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
	GPIO_Init(CTL_JMP2_PORT, &GPIO_InitStructure);
}
